package team.star.werespos.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import team.star.werespos.config.shiro.CurrPrincipal;
import team.star.werespos.model.vo.ResultVO;
import team.star.werespos.model.entity.User;
import team.star.werespos.model.enums.CodeMsgEnum;
import team.star.werespos.util.Result;

/**
 * GateWayController class<br/>
 * 鉴权跳转网关
 * @author hdonghong
 * @since 2019/04/21
 */
@RestController
public class GateWayController {

    @GetMapping("/index")
    public ResultVO<?> index() {
        return Result.success();
    }

    @GetMapping("/toLogin")
    public ResultVO<?> login() {
        return Result.error(CodeMsgEnum.LOG_IN);
    }

    @GetMapping("/unauthorized")
    public ResultVO<?> unauthorized() {
        return Result.error(CodeMsgEnum.UNAUTHORIZED);
    }

    @PostMapping("login")
    public ResultVO<?> login(@RequestBody User user) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());

        try {
            subject.login(token);
            return Result.success((User) subject.getPrincipal());

        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            return Result.error(CodeMsgEnum.USER_AUTHORIZE_FAIL);

        } catch (DisabledAccountException e) {
            return Result.error(CodeMsgEnum.USER_ACCOUNT_ERROR);
        }
    }

    @GetMapping("/logout")
    public ResultVO<?> logout() {
        CurrPrincipal.logout();
        return Result.success();
    }

    /**
     * 获取当前用户信息
     * */
    @GetMapping({"/user/profile"})
    public ResultVO<?> getProfile() {
        return Result.success(CurrPrincipal.get());
    }
}
